module.exports = (app) => {
  const { INTEGER, STRING, DATE, ENUM, TEXT } = app.Sequelize;
  const moment = require("moment");
  const crypto = require("crypto");
  // 配置（重要：一定要配置详细，一定要！！！）
  const User = app.model.define("user", {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: "主键ID"
    },
    avatar: {
      type: STRING(100),
      allowNull: false,
      defaultValue: "",
      comment: "头像"
    },
    username: {
      type: STRING(30),
      allowNull: false,
      defaultValue: "",
      comment: "用户名"
      // unique: true
    },
    email: {
      type: STRING(50),
      allowNull: false,
      defaultValue: "",
      comment: "邮箱"
    },
    phone: {
      type: STRING(11),
      allowNull: false,
      defaultValue: "",
      unique: true,
      comment: "手机号"
    },
    password: {
      type: STRING,
      allowNull: false,
      defaultValue: "",
      comment: "密码",
      set(val) {
        const hash = crypto.createHash("md5", app.config.crypto.secret);
        hash.update(val);
        this.setDataValue("password", hash.digest("hex"));
      }
    },
    desc: {
      type: TEXT,
      allowNull: true,
      comment: "描述"
    },
    status: {
      type: ENUM("0", "1"),
      allowNull: false,
      defaultValue: "1",
      comment: "状态 0 禁用 1 启用"
    },
    gender: {
      type: ENUM("0", "1", "2"),
      allowNull: false,
      defaultValue: "0",
      comment: "性别 0 未知 1 男 2 女"
    },
    roleId: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 1,
      comment: "角色ID"
    },
    memberId: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 7,
      comment: "会员ID"
    },
    created_time: {
      type: DATE,
      get() {
        const v = this.getDataValue("created_time");
        return v ? moment(v).format("YYYY-MM-DD HH:mm:ss") : v;
      }
    },
    updated_time: {
      type: DATE,
      get() {
        const v = this.getDataValue("created_time");
        return v ? moment(v).format("YYYY-MM-DD HH:mm:ss") : v;
      }
    }
  });

  // 定义关联
  User.associate = () => {
    app.model.User.belongsTo(app.model.Role, {
      foreignKey: "roleId",
      targetKey: "id"
      // as: "role"
    });
    app.model.User.belongsTo(app.model.Member, {
      foreignKey: "memberId",
      targetKey: "id"
    });
  };

  return User;
};
